package com.ja.openchat.ui;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.databinding.Observable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.google.gson.JsonObject;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityMainBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.contact.ContactDetailSingleActivity;
import com.ja.openchat.ui.contact.ContactFragment;
import com.ja.openchat.ui.contact.ContactNewFragment;
import com.ja.openchat.ui.dialog.CheckChatInviteLinkDialog;
import com.ja.openchat.ui.found.FoundFragment;
import com.ja.openchat.ui.login.LoginByPCActivity;
import com.ja.openchat.ui.me.MeFragment;
import com.ja.openchat.ui.message.DoubleClickListener;
import com.ja.openchat.ui.message.MsgFragment;
import com.ja.openchat.viewmodels.MainViewModel;
import com.ja.openchat.views.ChatUserDialog;
import com.ja.openchat.views.SpecialMWTab;
import com.ja.openchat.views.SpecialTab;
import com.ja.openchat.views.SpecialTabRound;
import com.ja.openchat.views.SpecialUrlTab;
import com.lqr.emoji.StickerManager;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.util.XPopupUtils;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.RedPacketManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.TabExMenuInfo;
import com.zy.openchat.core.model.group.ChatInviteLink;
import com.zy.openchat.core.model.group.RequestData;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.BadgeUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StatusBarUtil;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;
import pub.devrel.easypermissions.EasyPermissions;
import q.rorbin.badgeview.QBadgeView;

import static com.ja.openchat.ui.SplashActivity.PERMISSIONS_BASIC;
import static com.ja.openchat.ui.SplashActivity.REQUEST_BASIC;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainViewModel> {


    private List<Fragment> mFragments;
    private DoubleClickListener doubleClickListener;

    private MsgFragment msgFragment;
    private ContactNewFragment contactNewFragment;
    private FoundFragment foundFragment;
    private MeFragment meFragment;
    private TabExWebFragment tabExWebFragment;

    private BaseTabItem baseTabItem;
    private BaseTabItem contactTabItem ;
    private BaseTabItem fundTabItem ;
    private BaseTabItem meTabItem ;
    private BaseTabItem webTabItem ;

    public static void start(Activity activity) {
        start(activity, null,null,null);
    }


    public static void start(Activity activity, String action, Bundle extras, Uri data) {
        Intent intent = new Intent();
        if (!TextUtils.isEmpty(action)) {
            intent.setAction(action);
        }
        if (extras != null) {
            intent.putExtras(extras);
        }
        if(data!=null){
            intent.setData(data);
        }
        intent.setClass(activity, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public MainViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MainViewModel.class);
    }

    @Override
    public void setStatusBar() {

    }

    @Override
    public void initImmersionBar() {
//        ImmersionBar.with(this)
//                .navigationBarColor("#ffffff")
//                .statusBarDarkFont(true)
//                .fitsSystemWindows(false)
//                .statusBarColor("#00000000").init();
    }

    @Override
    public void initView() {
        super.initView();
        mFragments = new ArrayList<>();

        resetTab();

        viewModel.mTabExMenuInfoEvent.observe(this, new Observer<TabExMenuInfo>() {
            @Override
            public void onChanged(TabExMenuInfo exMenuInfo) {
                resetTab();
                if (exMenuInfo != null&& exMenuInfo.isValid()){
                    if(webTabItem != null){
                        webTabItem.setTitle(exMenuInfo.title);
                        SpecialUrlTab tab = (SpecialUrlTab) webTabItem;
                        tab.setIconUrl(exMenuInfo.icon);
                    }
                }
            }
        });
    }

    private void resetTab(){

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        List<Fragment> list = getSupportFragmentManager().getFragments();
        for(Fragment fragment: list){
            transaction.remove(fragment).commitNowAllowingStateLoss();
        }

        String middleTitle = getResources().getString(R.string.home_explore);
        String iconUrl = "";
        String status = "";
        //扩展菜单
        TabExMenuInfo curTabExMenuInfo = TabExMenuInfo.getTabExMenuInfo();
        if (curTabExMenuInfo != null && curTabExMenuInfo.isValid()) {
            middleTitle = curTabExMenuInfo.title;
            iconUrl = curTabExMenuInfo.icon;
            status = curTabExMenuInfo.status;
        }

        mFragments.clear();

        tabExWebFragment = new TabExWebFragment();
        msgFragment = new MsgFragment();
        contactNewFragment = new ContactNewFragment();
        foundFragment = new FoundFragment();
        meFragment = new MeFragment();

        mFragments.add(msgFragment);
//        mFragments.add(new ContactFragment());
        mFragments.add(contactNewFragment);
        if(TextUtils.equals(status,"1")){
            mFragments.add(tabExWebFragment);
        }
        mFragments.add(foundFragment);
        mFragments.add(meFragment);

        //默认选中第一个
        commitAllowingStateLoss(0);

//        BaseTabItem baseTabItem = newItem(R.mipmap.home, R.mipmap.home_sel, getResources().getString(R.string.home_msg));
//        BaseTabItem contactTabItem = newItem(R.mipmap.contact, R.mipmap.contact_sel, getResources().getString(R.string.home_contacts));
//        BaseTabItem fundTabItem = newItem(R.mipmap.found, R.mipmap.found_sel, getResources().getString(R.string.home_discover));
//        BaseTabItem meTabItem = newItem(R.mipmap.my, R.mipmap.my_sel, getResources().getString(R.string.home_my));
//        BaseTabItem webTabItem = newRoundItem(R.mipmap.explore, R.mipmap.explore_sel, middleTitle);
//        NavigationController navigationController = binding.pagerBottomTab.custom()
//                .addItem(baseTabItem)
//                .addItem(contactTabItem)
//                .addItem(webTabItem)
//                .addItem(fundTabItem)
//                .addItem(meTabItem)
//                .build();

        baseTabItem = newItemMW(R.drawable.tab_icon_message_default, R.raw.home_s, getResources().getString(R.string.home_msg));
        contactTabItem = newItemMW(R.drawable.tab_icon_txl_default, R.raw.conta, getResources().getString(R.string.address_book));
        fundTabItem = newItemMW(R.drawable.tab_icon_home_default, R.raw.explore, getResources().getString(R.string.explore_text));
        meTabItem = newItemMW(R.drawable.tab_icon_my_default, R.raw.mine, getResources().getString(R.string.home_my));
        webTabItem = newItemUrl(iconUrl, middleTitle);
        PageNavigationView.CustomBuilder customBuilder = binding.pagerBottomTab.custom();
        if(TextUtils.equals(status,"1")){
            customBuilder.addItem(baseTabItem)
                    .addItem(contactTabItem)
                    .addItem(webTabItem)
                    .addItem(fundTabItem)
                    .addItem(meTabItem);
        }else {
            customBuilder.addItem(baseTabItem)
                    .addItem(contactTabItem)
                    .addItem(fundTabItem)
                    .addItem(meTabItem);
        }
        NavigationController navigationController = customBuilder
                .enableAnimateLayoutChanges()
                .build();



        //底部按钮的点击事件监听
        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                commitAllowingStateLoss(index);
            }

            @Override
            public void onRepeat(int index) {
                if(index == 0){
                    if (doubleClickListener != null) {
                        doubleClickListener.doubleClick();
                    }
                }
            }
        });

        QBadgeView qBadgeView = new QBadgeView(this);
        qBadgeView.setBadgeTextSize(11, true);
        qBadgeView.setGravityOffset(17, 0, true);

        qBadgeView.bindTarget(baseTabItem).setBadgeNumber(viewModel.msgUnreadTotalCount.get())
                .setShowShadow(true)
                .setBadgeGravity(Gravity.TOP | Gravity.END);
        viewModel.msgUnreadTotalCount.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                int count = viewModel.msgUnreadTotalCount.get();
                Integer circle = viewModel.mCircleUnreadCount.getValue();
                int total = count + (circle==null?0:circle);
                BadgeUtils.setCount(total,MainActivity.this);
                qBadgeView.setBadgeNumber(count);
            }
        });


        QBadgeView qBadgeViewFund = new QBadgeView(this);
        qBadgeViewFund.setBadgeTextSize(11, true);
        qBadgeViewFund.setGravityOffset(17, 0, true);
        qBadgeViewFund.bindTarget(fundTabItem)
                .setShowShadow(true)
                .setBadgeGravity(Gravity.TOP | Gravity.END);
        viewModel.mCircleUnreadCount.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer != null){
                    qBadgeViewFund.setBadgeNumber(integer);
                    int total = integer+viewModel.msgUnreadTotalCount.get();
                    BadgeUtils.setCount(total,MainActivity.this);
                }


            }
        });
        Integer circle = viewModel.mCircleUnreadCount.getValue();
        int total = (circle==null?0:circle)+viewModel.msgUnreadTotalCount.get();
        BadgeUtils.setCount(total,MainActivity.this);
    }


    private void commitAllowingStateLoss(int position) {
        String status = "";
        //扩展菜单
        TabExMenuInfo curTabExMenuInfo = TabExMenuInfo.getTabExMenuInfo();
        if (curTabExMenuInfo != null && curTabExMenuInfo.isValid()) {
            status = curTabExMenuInfo.status;
        }
        if(TextUtils.equals(status,"1")) {
            switch (position){
                case 4:
                    ImmersionBar.with(this)
                            .navigationBarColor("#ffffff")
                            .statusBarDarkFont(true)
                            .fitsSystemWindows(false)
                            .statusBarColor("#00000000").init();
                    break;
                case 3:
                    ImmersionBar.with(this)
                            .navigationBarColor("#ffffff")
                            .statusBarDarkFont(true)
                            .fitsSystemWindows(true)
                            .statusBarColor("#f7f7f7").init();
                    break;
                default:
                    ImmersionBar.with(this)
                            .navigationBarColor("#ffffff")
                            .statusBarDarkFont(true)
                            .fitsSystemWindows(true)
                            .statusBarColor("#ffffff").init();
                    break;
            }
        }else {
            switch (position){
                case 3:
                    ImmersionBar.with(this)
                            .navigationBarColor("#ffffff")
                            .statusBarDarkFont(true)
                            .fitsSystemWindows(false)
                            .statusBarColor("#00000000").init();
                    break;
                case 2:
                    ImmersionBar.with(this)
                            .navigationBarColor("#ffffff")
                            .statusBarDarkFont(true)
                            .fitsSystemWindows(true)
                            .statusBarColor("#f7f7f7").init();
                    break;
                default:
                    ImmersionBar.with(this)
                            .navigationBarColor("#ffffff")
                            .statusBarDarkFont(true)
                            .fitsSystemWindows(true)
                            .statusBarColor("#ffffff").init();
                    break;
            }
        }

        hideAllFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(position + "");
        if (currentFragment != null) {
            transaction.show(currentFragment);
        } else {
            currentFragment = mFragments.get(position);
            transaction.add(R.id.frameLayout, currentFragment, position + "");
        }
        if(position == 0){
            doubleClickListener = (MsgFragment)currentFragment;
        }
        transaction.commitAllowingStateLoss();

        viewModel.syncTabExMenu();
    }

    //隐藏所有Fragment
    private void hideAllFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mFragments.size(); i++) {
            Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(i + "");
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    /**
     * 正常tab
     */
    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(0xFF888888);
        mainTab.setTextCheckedColor(getResources().getColor(R.color.colorAccent));
        return mainTab;
    }

    private BaseTabItem newItemUrl(String iconUrl, String text) {
        SpecialUrlTab mainTab = new SpecialUrlTab(this);
        mainTab.initialize(iconUrl, text);
        mainTab.setTextDefaultColor(0xFF888888);
        mainTab.setTextCheckedColor(getResources().getColor(R.color.login_btn_bg_color_green));
        return mainTab;
    }

    private BaseTabItem newItemMW(int drawable, int checkedDrawable, String text) {
        SpecialMWTab mainTab = new SpecialMWTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(0xFF888888);
        mainTab.setTextCheckedColor(getResources().getColor(R.color.login_btn_bg_color_green));
        return mainTab;
    }

    /**
     * 圆形tab
     */
    private BaseTabItem newRoundItem(int drawable, int checkedDrawable, String text) {
        SpecialTabRound mainTab = new SpecialTabRound(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(0xFF888888);
        mainTab.setTextCheckedColor(getResources().getColor(R.color.colorAccent));
        return mainTab;
    }

    @Override
    public void initData() {
        super.initData();

        //刷新未读总数
        viewModel.refreshUnreadCountView();
        //同步联系人
        TelegramManager.getTelegramManager().syncMyContacts();
        //加载会话
        TelegramManager.getTelegramManager().getChatListIds(this, new TgResultBlock<Object>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, Object obj) {
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
            }
        });
        //处理通知
        viewModel.doNotificationIntent(getIntent());
        //版本检测
        viewModel.silentUpdate(this);

        viewModel.isHandleViewIntent.set(true);

        OuterShareActivity.handleShareIntent(this, getIntent());

        TelegramManager.getTelegramManager().doregisterDevice();
        RedPacketManager.getRedPacketManager().refresh();


        if (!EasyPermissions.hasPermissions(this, PERMISSIONS_BASIC)) {
            EasyPermissions.requestPermissions(this,
                    String.format(getString(R.string.permission_basic_tip), getString(R.string.app_name)),
                    REQUEST_BASIC, PERMISSIONS_BASIC);
        }
        Constants.MEDIA_MAX_WIDTH = (int) (XPopupUtils.getAppWidth(this) * 0.74);

        StickerManager.getInstance().refreshStickerCategory();

        TelegramManager.getTelegramManager().setUserState(true);


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        viewModel.isHandleViewIntent.set(true);
        viewModel.doNotificationIntent(intent);
    }


    @Override
    protected void onResume() {
        super.onResume();
        OuterShareActivity.isStartMain = true;
        //清除通知
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        //同步数据
        viewModel.syncServerData(MainActivity.this);

        if (OuterShareActivity.isStartMain && UserInfo.getUserInfo().id > 0 && TextUtils.isEmpty(UserInfo.getUserInfo().displayName())) {
            TelegramManager.getTelegramManager().requestContactInfo(this, UserInfo.getUserInfo().id, new TgResultBlock<UserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {

                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        onScanResult(MainActivity.this, requestCode, resultCode, data);
        onScanResult1(MainActivity.this, requestCode, resultCode, data);
    }

    public static void onScanResult(BaseActivity activity, int requestCode, int resultCode, Intent result) {
        KLog.d("onScanResult==" + requestCode + "--" + resultCode);
        if (result != null ) {
            String scanContent = result.getStringExtra("scanContent");
            KLog.d("scanContent==" + scanContent);
            if (TextUtils.isEmpty(scanContent)) {
                //showWarnTip("无效二维码");
            } else if (scanContent.contains("login")) {
//                ScanLoginHintActivity.start(activity,scanContent);
                Intent intent = new Intent(activity, LoginByPCActivity.class);
                intent.putExtra("scanContent", scanContent);
                activity.startActivity(intent);
            } else {
                long uid = UserInfo.userIdFromQrString(scanContent);
                if (uid <= 0) {
                    toGroupContactDetailView(activity, scanContent);
                } else {
//                    toContactDetailView(activity, uid);
                }
            }
        }
    }

    public void onScanResult1(BaseActivity activity, int requestCode, int resultCode, Intent result) {
        KLog.d("onScanResult==" + requestCode + "--" + resultCode);
        if (result != null ) {
            String scanContent = result.getStringExtra("scanContent");
            KLog.d("scanContent==" + scanContent);
            if (TextUtils.isEmpty(scanContent)) {

            } else if (scanContent.contains("login")) {

            } else {
                long uid = UserInfo.userIdFromQrString(scanContent);
                if (uid <= 0) {

                } else {
                    toContactDetailView(activity, uid);
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        if(binding.pagerBottomTab.curre)
    }

    public static void toGroupContactDetailView(BaseActivity activity, String invite_link) {
        activity.showProgress();
        TelegramManager.getTelegramManager().checkChatInviteLink(activity, invite_link, true, new TgResultBlock<RequestData<ChatInviteLink>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, RequestData<ChatInviteLink> obj) {
                activity.hideProgress();
                if (obj != null && obj.isOk && obj.data != null) {
                    obj.data.invite_link = invite_link;
                    new XPopup.Builder(activity)
                            .asCustom(new CheckChatInviteLinkDialog(activity, obj.data))
                            .show();
                } else if (obj != null && obj.data != null && obj.data.chatInfo != null) {
                    ChatActivity.startActivity(activity, obj.data.chatInfo);
                } else if (obj != null && !TextUtils.isEmpty(obj.errorMsg)) {
                    activity.showErrorTip(obj.errorMsg);
                } else {
                    activity.showErrorTip(activity.getString(R.string.invalid_qr_code));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                activity.hideProgress();
                activity.showErrorTip(activity.getString(R.string.invalid_qr_code));
            }
        });
    }


    public void toContactDetailView(BaseActivity activity, long uid) {
        activity.showProgress();
        TelegramManager.getTelegramManager().requestContactInfo(activity, uid, new TgResultBlock<UserInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserInfo obj) {
                activity.hideProgress();
                if (obj != null) {
//                    ContactDetailActivity.start(activity, obj);
//                    ContactDetailSingleActivity.start(activity, obj);
//                    boolean blockContact = !(chatInfo.permissions != null && !chatInfo.permissions.banWhisper);
                    View view = findViewById(R.id.frameLayout);
                    new XPopup.Builder(activity)
                            .hasShadowBg(true)
                            .isDestroyOnDismiss(true)
                            .dismissOnTouchOutside(true)
                            .borderRadius(10)
                            .atView(view)
                            .asCustom(new ChatUserDialog(activity, obj,false, new ChatUserDialog.OnItemClickListner() {
                                @Override
                                public void clickPostion(int postion, ChatInfo chatInfo) {

                                }
                            })).show();
                } else {
                    activity.showErrorTip(activity.getString(R.string.request_error));
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                activity.hideProgress();
                activity.showErrorTip(activity.getString(R.string.request_error));
            }
        });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}